<script setup>
import {ref} from 'vue'
import {LoginUser} from '@/api/login.js'
import {ElMessage} from 'element-plus'
//登陆成功后要跳转到首页
import router from '@/router/index'
//定义登录的表单数据
const loginForm = ref({username: '', password: ''})

//引用表单
const ruleFormRef = ref(null)
//表单验证
const rules = ref({
  username: [
    {required: true, message: '账号不能为空', trigger: 'blur'},
    {min: 2, max: 50, message: '长度在2-50个字符', trigger: 'blur'},
  ],
  password: [
    {required: true, message: '密码不能为空', trigger: 'blur'},
    {min: 2, max: 50, message: '长度在2-50个字符', trigger: 'blur'},
  ]
})

//登录的点击事件，来发起登录请求
const login = () => {
  // const result = await LoginUser(loginForm.value)
  //表单校验通过才会执行
  if (!ruleFormRef) return
  ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      //校验通过才会执行
      const result = await LoginUser(loginForm.value)
      if (result.code) {
        localStorage.setItem('userToken', JSON.stringify(result.data))
        ElMessage.success('登陆成功')
        //登录成功要跳转到首页
        router.push('/index')
      } else {
        ElMessage.error('登陆失败！请重新登录')
      }
    } else {
      ElMessage.error('登录校验失败，请重新登录！')
    }
  })
}

//取消登录的点击事件
const clear = () => {
  loginForm.value = {username: '', password: ''}
  if (!ruleFormRef.value) return
  ruleFormRef.value.resetFields()
}
</script>


<template>
  <div id="container">
    <div class="left-side">
      <img src="../../assets/cangku02.png" alt="仓库管理系统插图" class="login-image">
    </div>
    <div class="right-side">
      <el-form label-width="80px" :rules="rules" ref="ruleFormRef" :model="loginForm" :hide-required-asterisk="true">
        <!-- <p class="title">WMS仓库管理系统</p> -->
        <p class="title">欢迎来到仓储系统</p>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="loginForm.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="button" type="primary" @click="login" plain>登 录</el-button>
          <el-button class="button" type="info" @click="clear" plain>取 消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
#container {
  display: flex;
  height: 100vh;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

.left-side {
  flex: 7; /* 图片占70% */
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
}

.login-image {
  max-width: 100%;
  height: auto;
}

.right-side {
  flex: 3; /* 登录区域占30% */
  padding: 30px;
  background-color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.title {
  font-size: 30px;
  /*font-family: '楷体';*/
  text-align: center;
  margin-bottom: 30px;
  font-weight: bold;
}

.button {
  margin-top: 30px;
  width: 120px;
}
</style>